package com.heima.article.listen;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @作者 itcast
 * @创建日期 2021/9/26 14:26
 **/
@Component
@Slf4j
public class ArticleUpOrDownListener {

    @Autowired
    ApArticleConfigService apArticleConfigService;

    @RabbitListener(queuesToDeclare = {@Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ARTICLE_CONFIG_QUEUE)})
    public void articleUpHandler(@Payload String articleId, Message message, Channel channel){
        log.info("接收到 文章上架的消息， 文章的id: {}",articleId);
        try {
        // 修改上架
            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .set(ApArticleConfig::getIsDown,false)
                    .eq(ApArticleConfig::getArticleId,Long.valueOf(articleId))
            );
        // 确认消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("文章上架消息处理成功   文章id:{}",articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文章上架消息处理失败   文章id:{}   失败原因: {}",articleId,e.getMessage());
        }
    }
    @RabbitListener(queuesToDeclare = {@Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ARTICLE_CONFIG_QUEUE)})
    public void articleDownHandler(@Payload String articleId, Message message, Channel channel){
        log.info("接收到 文章下架的消息， 文章的id: {}",articleId);
        try {
            // 修改上架
            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .set(ApArticleConfig::getIsDown,true)
                    .eq(ApArticleConfig::getArticleId,Long.valueOf(articleId))
            );
            // 确认消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("文章下架消息处理成功   文章id:{}",articleId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文章下架消息处理失败   文章id:{}   失败原因: {}",articleId,e.getMessage());
        }
    }
}
